import { ref } from 'vue';
import { REQU, SignInInfoInvalidCondPair, toFormData, useResp } from '@/net/requ.js';
import { Modal, message } from 'ant-design-vue';
import router from '@/router/index.js';
import { PkgListReadOf, NextPkgId } from '@/util/index.js';
import * as storage from '@/util/storage.js';

/**
 * `pre` 调接口前做某事
 * `Params` 生成题相关的参数 `packageId`, `assignedFileId` 等
 */
export function CustomJudge({ pre, Params, quesJudged, pkgJudged }) {
  /** @param {{ pass: boolean; wholePackagePass: boolean; remark: string; }} params  */
  return function judge(params) {
    pre();
    return REQU('/api/task/assignedFileAudit', {
      method: 'POST',
      body: toFormData(R.mergeRight(params, Params(params))),
    })
    .then(useResp({
      succ: result => {
        R.cond([
          [R.has('pass'), quesJudged],
          [R.has('wholePackagePass'), pkgJudged],
        ])(params);
      },
      fail: R.cond([
        [
          R.compose( R.equals(-3), Number, R.prop('code') ),
          R.compose( R.tap(message.error), R.prop('message') )
        ],
        [
          R.compose( R.equals(500), Number, R.prop('status') ),
          R.compose( R.tap(message.error), R.prop('error') )
        ],
        SignInInfoInvalidCondPair(),
      ]),
    }));
  }
}

export function CustomShowConfirmNextPkg({ confirmModalProps, taskInfo, switchable, toNextPkg }) {
  return function showConfirmNextPkg(content) {
    confirmModalProps.value.visible = true;

    switchable()
    ? Modal.confirm({
        centered: true,
        content,
        okText: '开始下一包',
        onOk: async () => {
          confirmModalProps.value.visible = false;
          const nextPkgId = R.compose( NextPkgId, PkgListReadOf, R.prop('user'), storage.readAsObj )('pkgInfo');
          const nextPkgInfo = Object.assign(storage.readAsObj('pkgInfo'), { pkg: nextPkgId });
          await toNextPkg(nextPkgInfo);
        },
        cancelText: '返回任务详情',
        onCancel: () => {
          confirmModalProps.value.visible = false;
          router.push({ path: '/task-detail', query: { id: taskInfo.value.id } });
        },
      })
    : Modal.success({
        centered: true,
        content: '最后一包审核完毕',
        okText: '返回任务详情',
        onOk: () => {
          confirmModalProps.value.visible = false;
          router.push({ path: '/task-detail', query: { id: taskInfo.value.id } });
        },
        onCancel: () => confirmModalProps.value.visible = false,
      });
  }
}

export function useJudge() {
  const confirmModalProps = ref({ visible: false });
  
  const judgeModalProps = ref({ visible: false });
  function useJudgeModal(o) {
    Object.assign(judgeModalProps.value, { visible: true, all: false }, o);
  }

  const commentModalProps = ref({ visible: false });

  return {
    confirmModalProps,
    judgeModalProps,
    useJudgeModal,
    commentModalProps,
  };
}
